package cn.itcast.bos.action.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.springframework.data.domain.Page;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 抽取Action的公共代码，简化开发
 * */
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//模型驱动
	protected T model;
	
	@Override
	public T getModel() {
		return model;
	}

	//通过构造器完成model实例化
	public BaseAction(){
		
		//构造子类Action对象，获取继承父类型的泛型
		//AreaAction extends BaseAction<Area>
		//BaseAction<Area>
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		
		//获取类型第一个泛型参数
		ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
		
		@SuppressWarnings("unchecked")
		Class<T> modelClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
	
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型构造失败");
		}
	}
	
	//属性驱动接收分页请求参数
		protected int page;
		protected int rows;
		
		public void setPage(int page) {
			this.page = page;
		}

		public void setRows(int rows) {
			this.rows = rows;
		}
		
		//将返回的Page对象进行转换，转为datagrid需要的形式
		protected void pushPageDataToValueStack(Page<T> pageData){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("total", pageData.getTotalElements());
			map.put("rows", pageData.getContent());
			
			//将传后的结果压入值栈转换为jso返回给datagrid
			ActionContext.getContext().getValueStack().push(map);
		}
		
}
